package com.haoran.dwz.config;

import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.haoran.dwz.service.DwzService;
import com.haoran.dwz.service.impl.DwzServiceOkHttpImpl;
import com.squareup.okhttp.OkHttpClient;

@Configuration
public class OkHttpConfig {
	@Value("${http.timeout.connect:5000}")
	private long connectTimeout;
	@Value("${http.timeout.read:5000}")
	private long readTimeout;
	@Value("${http.timeout.write:5000}")
	private long writeTimeout;
	
	@Bean
	public DwzService dwzService() {
		return new DwzServiceOkHttpImpl();
	}
	
	@Bean
	public OkHttpClient okHttpClient() {
		OkHttpClient okHttpClient = new OkHttpClient();
		okHttpClient.setConnectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
		okHttpClient.setReadTimeout(readTimeout, TimeUnit.MILLISECONDS);
		okHttpClient.setWriteTimeout(writeTimeout, TimeUnit.MILLISECONDS);
		return okHttpClient;
	}

	@Bean
	@Primary
	public OkHttpClient getUnsafeOkHttpClient() {

		try {
			X509TrustManager s = new X509TrustManager() {
				@Override
				public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
						throws CertificateException {
				}

				@Override
				public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
						throws CertificateException {
				}

				@Override
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};
			// Create a trust manager that does not validate certificate chains
			final TrustManager[] trustAllCerts = new TrustManager[] { s };
			// Install the all-trusting trust manager
			final SSLContext sslContext = SSLContext.getInstance("SSL");
			sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
			// Create an ssl socket factory with our all-trusting manager
			final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

			OkHttpClient okHttpClient = new OkHttpClient();
			okHttpClient.setSslSocketFactory(sslSocketFactory);
			okHttpClient.setHostnameVerifier(new HostnameVerifier() {
				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			});
			return okHttpClient;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
